{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## **演示0504：拉格朗日乘子法**"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### **问题提出**\n",
    "拉格朗日乘子法（Lagrange multiplier）用于解决在某种约束条件下对某个函数求极值的问题。\n",
    "* 假设某目标函数：$f(x,y)$， 在无约束条件下，只要求出该函数导数为0时的$(x_0,y_0)$值，然后再代入$f(x_0,y_0)$求取极值即可。\n",
    "* 如果在求极值的同时，还需要满足约束条件$g(x,y)=c$，或$g(x,y)-c=0$；就需要使用拉格朗日乘子法。\n",
    "* 下图画出了目标函数$f(x,y)$的等值线图(蓝色虚线)，同时画出了约束函数$g(x,y)$的曲线图（红色实线）。$g(x,y)=c$与某条等值线的切点（图中的$d_1$点），就是$f(x,y)$的极值点。只需要把该极值点的$(x,y)$代入回$f(x,y)$中，就能求得目标函数$f(x,y)$在约束条件$g(x,y)=c$下的极值。\n",
    "* 同时请注意，函数$f(x,y)$和$g(x,y)=c$在切点$d_1$处的法向量共线(但不一定同向)\n",
    "\n",
    "![](../images/050401.png)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### **计算过程**\n",
    "假设目标函数$f(x,y)$以及约束条件：$g(x,y)=c$。  \n",
    "要求目标函数的极值，等价于求下列函数的极值：  \n",
    "$ F(x,y,\\lambda)=f(x,y)+ \\lambda (g(x,y)-c)$    \n",
    "其中，$\\lambda$是一个不为0的标量\n",
    "* 将$F$函数分别对$x,y,\\lambda$求偏导数，并使其偏导数为0  \n",
    "$ \\left\\{\\begin{array}{lcr}\n",
    "\\dfrac{\\partial F}{\\partial x} = 0 \\\\\n",
    "\\dfrac{\\partial F}{\\partial y} = 0 \\\\\n",
    "\\dfrac{\\partial F}{\\partial \\lambda} = 0\n",
    "\\end{array}\\right. $\n",
    "* 多个约束条件的情形\n",
    " * 在多个约束条件$g_1(x, y)=c_1$和$g_2(x, y)=c_2$ 情况下, $F(x,y,\\lambda_1,\\lambda_2)=f(x,y)+ \\lambda_1 (g_1(x,y)-c_1 )+\\lambda_2 (g_2(x,y)-c_2)$\n",
    " * 再对$x,y, \\lambda_1,\\lambda_2$ 分别求偏导数"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### **案例1：**\n",
    ">已知目标函数：$f(x_1, x_2, x_3 )=2x_1^2+ 3x_2^2+7x_3^2$，约束函数：$g_1=2x_1+x_2-1$，$g_2=2x_2+3x_3-2$，计算其极值  \n",
    "* 应用乘子法之后的函数：  \n",
    "$ F(x_1,x_2,x_3,\\lambda_1,\\lambda_2 )= 2x_1^2+ 3x_2^2+7x_3^2+\\lambda_1 (2x_1+x_2-1)+\\lambda_2 (2x_2+3x_3-2) $  \n",
    "* 列出偏导方程式：  \n",
    "$ \\left\\{\\begin{array}{lcr}\n",
    "\\dfrac{\\partial F}{\\partial x_1}=4 x_1+2 \\lambda_1=0 \\\\\n",
    "\\dfrac{\\partial F}{\\partial x_2}=6 x_2+\\lambda_1+2 \\lambda_2=0 \\\\\n",
    "\\dfrac{\\partial F}{\\partial x_3}=14 x_3+3 \\lambda_2=0 \\\\\n",
    "\\dfrac{\\partial F}{\\partial \\lambda_1}=2 x_1+x_2-1=0 \\\\\n",
    "\\dfrac{\\partial F}{\\partial \\lambda_2}=2 x_2+3 x_3-2=0\n",
    "\\end{array}\\right. $  \n",
    "* 可解得：$\\lambda_1=-0.45,\\lambda_2=-1.41,x_1=0.227,x_2=0.546,x_3=0.302$，对应的极值为$f(0.227,0.546,0.302)$"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.8.2"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 4
}
